#!/usr/bin/env bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

openEuler_mirror="http://repo.huaweicloud.com/openeuler"
openEuler_version="openEuler-21.09"
openEuler_arch="x86_64"
openEuler_vncpassword="DEADBEEF"

openEuler_repo="${openEuler_mirror}/${openEuler_version}/OS/${openEuler_arch}"
openEuler_dir="/openEuler"

network_dhcp=0
network_ns="119.29.29.29"
if [[ ${network_dhcp} -eq 1 ]] ; then
    grub_network="ip=dhcp nameserver=${network_ns}"
elif [[ ${network_dhcp} -eq 0 ]] ; then
    network_if="$(ip -4 route list default |grep -oE 'dev [[:graph:]]+' |cut -d ' ' -f 2)"
    network_gw="$(ip -4 route list default |grep -oE 'via [[:graph:]]+' |cut -d ' ' -f 2)"
    network_ip="$(ifconfig ${network_if} |grep -oE 'inet [[:graph:]]+' |cut -d ' ' -f 2)"
    network_nm="$(ifconfig ${network_if} |grep -oE 'netmask [[:graph:]]+' |cut -d ' ' -f 2)"
    grub_network="ip=${network_ip}::${network_gw}:${network_nm}:::none nameserver=${network_ns}"
fi

grub_boot_uuid="$(cat /proc/cmdline |grep -oE 'root=[[:graph:]]+' |cut -d '=' -f 3)"

if [[ $(id -u) -ne 0 ]] ; then
    echo "Please run as root."
    exit 1
fi

if [[ "$(grub-install --version |grep -oE ' [0-9.]+' |sed 's/ \(.*\)/\1\n0.98/' |sort -rV |head -n 1)" == "0.98" ]] ; then
    echo "The script does not support GRUB legacy, please upgrade to GRUB2."
    exit 1
fi

mkdir -p "${openEuler_dir}"
for boot_file in "vmlinuz" "initrd.img"
do
    wget "${openEuler_repo}/isolinux/${boot_file}" -O "${openEuler_dir}/${boot_file}" -t 2
    wget_err=$?
    if [[ ${wget_err} -ne 0 ]] ; then
        echo "File \"${openEuler_repo}/isolinux/${boot_file}\" download failed! The script has exited."
        exit ${wget_err}
    fi
done

cat >> /etc/grub.d/40_custom <<EOF

menuentry 'NetInstall ${openEuler_version}' {
    load_video
    insmod xzio
    insmod part_msdos
    insmod ext2
    search --no-floppy --fs-uuid --set=root ${grub_boot_uuid}
    linux16 ${openEuler_dir}/vmlinuz initrd=initrd.magic ${grub_network} inst.repo=${openEuler_repo} inst.vnc inst.vncpassword=${openEuler_vncpassword}
    initrd16 ${openEuler_dir}/initrd.img
}
EOF

sed -i 's/GRUB_DEFAULT=.*/GRUB_DEFAULT=saved/' /etc/default/grub

if which grub-mkconfig 2>/dev/null ; then
    grub-mkconfig -o /boot/grub/grub.cfg
    grub-reboot "NetInstall ${openEuler_version}"
elif which grub2-mkconfig 2>/dev/null ; then
    grub2-mkconfig -o /boot/grub2/grub.cfg
    grub2-reboot "NetInstall ${openEuler_version}"
else
    echo "Failed to update the Grub configuration file,"
    echo "please check whether the grub-mkconfig or grub2-mkconfig command exists."
    exit 1
fi
